package hander

import (
	"context"
	"fmt"
	"math/rand"
	"regexp"
	"rpc-server/basic/global"
	"rpc-server/model"
	__ "rpc-server/proto"
	"time"
)

type UserServer struct {
	__.UnimplementedStreamGreeterServer
}

func isValidMobile(mobile string) bool {
	pattern := `^1[3-9]\d{9}$`
	re := regexp.MustCompile(pattern)
	return re.MatchString(mobile)
}

func (c *UserServer) SendSms(_ context.Context, in *__.SendSmsRequest) (*__.SendSmsResponse, error) {

	if !isValidMobile(in.Mobile) {
		return nil, fmt.Errorf("手机号格式不正确")
	}

	set, _ := global.Rdb.SetNX(context.Background(), "SendSmsLimit:"+in.Mobile, 1, time.Second*60).Result()
	if !set {
		return &__.SendSmsResponse{
			Code:    200,
			Message: "短信发送过于频繁，请60秒后再试",
		}, nil
	}

	code := rand.Intn(9000) + 1000

	global.Rdb.Set(context.Background(), "SendSms"+in.Mobile, code, time.Minute*5)

	return &__.SendSmsResponse{
		Code:    200,
		Message: "发送验证码成功",
	}, nil
}

func (c *UserServer) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {

	if !isValidMobile(in.Mobile) {
		return nil, fmt.Errorf("手机号格式不正确")
	}

	var user model.User
	global.DB.Where("mobile=?", in.Mobile).Find(&user)

	if user.Id == 0 {
		newUser := model.User{
			Name:   "用户" + in.Mobile,
			Mobile: in.Mobile,
		}

		if err := global.DB.Create(&newUser).Error; err != nil {
			return nil, fmt.Errorf("注册失败")
		}
	}

	get := global.Rdb.Get(context.Background(), "SendSms"+in.Mobile)
	if get.Err() != nil {
		return nil, fmt.Errorf("验证码已过期")
	}

	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	
	global.Rdb.Del(context.Background(), "SendSms"+in.Mobile)

	return &__.LoginResponse{
		Id: int64(user.Id),
	}, nil
}
